<template>
  <div class="main-wraper">
    <el-breadcrumb class="breadcrumb page-title" separator=">">
      <el-breadcrumb-item :to="{ path: '/computerModelIndex' }">Computer model</el-breadcrumb-item>
      <el-breadcrumb-item>new/edit</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search-box">
      <el-form :inline="true" label-position="top" :rules="rules" :model="form" size="mini" ref="ruleForm"
               class="demo-ruleForm main-search-box" v-loading="loading">
        <el-row>
          <el-row>
            <el-form-item :label="$t('m.Brand')" prop="brandId">
              <el-select style="width: 200px" v-model="form.brandId" placeholder="">
                <el-option v-for="rg in brandJson" :key="rg.id" :label="rg.text" :value="rg.id"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item label="Model name" style="width: 200px;" prop="modelName">
            <el-input v-model="form.modelName" placeholder=""></el-input>
          </el-form-item>
        </el-row>
        <!-- 上传图片 -->
        <p class="upload-photos">Upload Photos</p>
        <div class="upload-box">
          <div style="text-align:left">
            <div class="photos-box">
              <div class="color-show">
                <div v-if="showPhoto[0].url" class="color-box">
                  <img :src="showPhoto[0].url"/>
                  <a href="javascript:;" @click='delImage(0,showPhoto[0].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[0].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,0)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[1].url" class="color-box">
                  <img :src="showPhoto[1].url"/>
                  <a href="javascript:;" @click='delImage(1,showPhoto[1].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[1].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,1)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[2].url" class="color-box">
                  <img :src="showPhoto[2].url"/>
                  <a href="javascript:;" @click='delImage(2,showPhoto[2].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[2].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,2)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[3].url" class="color-box">
                  <img :src="showPhoto[3].url"/>
                  <a href="javascript:;" @click='delImage(3,showPhoto[3].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[3].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,3)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[4].url" class="color-box">
                  <img :src="showPhoto[4].url"/>
                  <a href="javascript:;" @click='delImage(4,showPhoto[4].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[4].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,4)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[5].url" class="color-box">
                  <img :src="showPhoto[5].url"/>
                  <a href="javascript:;" @click='delImage(5,showPhoto[5].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[5].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,5)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[6].url" class="color-box">
                  <img :src="showPhoto[6].url"/>
                  <a href="javascript:;" @click='delImage(6,showPhoto[6].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[6].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,6)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
              <div class="color-show">
                <div v-if="showPhoto[7].url" class="color-box">
                  <img :src="showPhoto[7].url"/>
                  <a href="javascript:;" @click='delImage(7,showPhoto[7].id)'>
                    <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                  </a>
                </div>
                <div v-if="!showPhoto[7].url" class="color-box"
                     style="position: relative;top: 0;left: 0;z-index: 10;">
                  <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                    <input type="file" name="CoverImages" @change="getFile($event,7)" style="display: none;">
                  </label>
                  <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                        class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-row>
          <el-button
            @click="cancelPutForm"
            size="medium"
            type="info"
          >
            Cancel
          </el-button>
          <el-button
            @click.native="uploadSubmitForm()"
            size="medium"
            type="success"
          >
            Save
          </el-button>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
  import {
    saveComputerModel,
    EditComputerModel,
    saveComputerModelPhoto,
    getComputerModelDetail
  } from '../../../api/zxy_api.js';
  import Qs from "qs";
  import category from '../../../json/category'

  export default {
    data() {
      return {
        id: '',
        category: category,
        form: {
          brandId: '',
          modelName: '',
        },
        brandJson: [],
        // 为调试方便临时把loading设成false，最后要记得改成true
        loading: false,
        rules: {
          brandId: [
            {required: true, message: 'please select brand', trigger: 'blur'}
          ],
          modelName: [
            {required: true, message: 'please enter model name', trigger: 'change'}
          ],
        },
        //显示图片的数组
        showPhoto: [
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
        ],
        //提交图片的数组
        uploadPhoto: [],
        //删除图片的id组成的数组
        images: [],
      }
    },
    methods: {
      // 获取图片文件
      getFile($event, index) {
        let file = $event.target.files[0];
        let reader = new FileReader()
        //reader.onload 后面接一个立即执行函数并且把file作为参数传进去
        reader.onload = ((theFile) => {
          return (e) => {
            this.setImageCompress(e, theFile, (imgObj) => {
              this.$set(this.showPhoto, index, {url: imgObj.photoUrl, id: ''})
              this.$set(this.uploadPhoto, index, imgObj.photoBlob)
            })
          }
        })(file)
        reader.readAsDataURL(file)
      },
      // 压缩图片
      setImageCompress(e, theFile, callback) {
        let img = new Image()
        img.src = e.target.result;
        let canvas = document.createElement('canvas')
        let context = canvas.getContext('2d')
        let self = this
        img.onload = function () {
          // 图片原始尺寸
          let originWidth = this.width
          let originHeight = this.height
          // 最大尺寸限制
          let maxWidth = 1000
          let maxHeight = 1000
          // 目标尺寸
          let targetWidth = originWidth
          let targetHeight = originHeight
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth
              targetHeight = Math.round(maxWidth * (originHeight / originWidth))
            } else {
              targetHeight = maxHeight
              targetWidth = Math.round(maxHeight * (originWidth / originHeight))
            }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth
          canvas.height = targetHeight
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight)
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight)
          // canvas转为blob并上传
          canvas.toBlob((blob) => {
            let srcUrl = URL.createObjectURL(blob)
            let imgObj = {
              photoUrl: srcUrl,
              photoBlob: blob,
              name: name,
            }
            callback(imgObj);
          }, 'image/jpeg', 0.9)
        }
      },
      // 删除图片 photos
      delImage(e, id) {
        this.showPhoto.splice(e, 1, '')
        this.uploadPhoto.splice(e, 1, '')
        if (id) {
          this.images.push(id)
        }
      },
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: "error"
        });
      },
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: "success"
        });
      },
      initForm() {
        let params = {}
        params.id = this.id
        getComputerModelDetail(params)
          .then(res => {
            this.loading = false
            if (res.data.errorID == 0) {
              let data = res.data.object

              this.form.brandId = Number(data.brandId)
              this.form.modelName = data.model

              //初始化删除图片ID数组
              this.images = []
              //图片数据初始化
              if (data.images.length > 0) {
                data.images.forEach(item => {
                  let obj = {}
                  obj.id = item.id
                  obj.url = item.url
                  this.showPhoto[item.sequence] = obj
                })
              }
            }
            else {
              this.messageToastErr(res.data.message)
            }
          })
          .catch(err => {
            console.log(err)
          })
      },
      cancelPutForm() {
        this.$router.go(-1);
      },
      // 表单信息上传
      uploadSubmitForm() {
        // 先验证是否有首图 没有就弹出消息提示

        if (!this.uploadPhoto[0] && !this.showPhoto[0].id) {
          this.messageToastErr('Cover Photo Is Required')
          return false
        }

        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.id) {
              let params = {
                id: this.id || '',
                brand: this.form.brandId || '',
                model: this.form.modelName || '',
                imageIds: JSON.stringify(this.images)
              };
              params = Qs.stringify(params);
              let config = {
                "Content-Type": "multipart/form-data"
              };
              this.loading = true;
              EditComputerModel(params, config)
                .then(res => {
                  if (res.data.errorID === 0) {
                    // this.messageToastSuccess("Edit Success");
                    // this.$router.push('/excelNameIndex')
                    let id = this.id;
                    this.sendFormPhotos(id)
                  }
                  else {
                    this.messageToastErr(res.data.message);
                    this.loading = false
                  }
                })
                .catch((err) => {
                  this.loading = false
                  console.dir(err)
                })
            } else {
              let params = {
                brand: this.form.brandId || '',
                model: this.form.modelName || '',
              };
              params = Qs.stringify(params);
              let config = {
                "Content-Type": "multipart/form-data"
              };
              this.loading = true;
              saveComputerModel(params, config)
                .then(res => {
                  if (res.data.errorID === 0) {
                    // this.messageToastSuccess("Edit Success");
                    // this.$router.push('/excelNameIndex')
                    let id = res.data.object.id
                    this.sendFormPhotos(id)
                  }
                  else {
                    this.messageToastErr(res.data.message);
                    this.loading = false
                  }
                })
                .catch((err) => {
                  this.loading = false
                  console.dir(err)
                })
            }
          } else {
            this.loading = false
            this.messageToastErr('The form information is incomplete, please check out')
          }
        })
      },
      // 多图上传
      sendFormPhotos(id) {
        let showPhotos = []
        let fileName = 'Photo'
        showPhotos = this.uploadPhoto
        let formData = new FormData()
        //  是否有图片提交，有则提交图片，没有则显示表单提交成功信息
        let isToUpload = false
        for (let i = 0; i < showPhotos.length; i++) {
          if (showPhotos[i]) {
            formData.append(fileName + '_' + i, showPhotos[i])
            isToUpload = true
          }
        }
        // 上传图片
        if (isToUpload) {
          this.loadingImage = true
          formData.append('id', id)
          let config = {
            'Content-Type': 'multipart/form-data'
          }
          //上传二进制图片文件
          this.loadingImage = true
          saveComputerModelPhoto(formData, config).then((res) => {
            this.loadingImage = false
            if (res.data) {
              if (res.data.errorID === 0) {
                this.loading = false
                this.messageToastSuccess("Edit Success");
                this.$router.push('/computerModelIndex')
              } else {
                this.loading = false
                this.messageToastErr('Upload picture failed, please try again leter')
              }
            }
          })
            .catch((error) => {
              this.loading = false
              console.log(error)
              this.messageToastErr('error, please try again later')
            })
        } else {
          this.loading = false
          this.messageToastSuccess("Edit Success eee");
          this.$router.push('/computerModelIndex');
        }
      },
    },
    mounted() {
      if (this.$route.query.id) {
        this.id = this.$route.query.id || "";
        this.initForm();
      }

      // 初始化brand
      for (let i = 0; i < this.category.length; i++) {
        if (this.category[i].id == '181') { // computer
          for (let j = 0; j < this.category[i].children.length; j++) {
            if (this.category[i].children[j].id == '183') {  // Laptops
              for (let k = 0; k < this.category[i].children[j].properties.length; k++) {
                if (this.category[i].children[j].properties[k].id == '11') {  // Computer Brand
                  this.brandJson = this.category[i].children[j].properties[k].values;
                }
              }
            }
          }
        }
      }

    }
  }
</script>
<style>
  .main-wraper {
    padding: 20px 40px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    border-bottom: 1px solid #eee;
  }
</style>
<style scoped>
  .model-title {
    font-weight: 700;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    margin: 6px 0;
  }

  /*新增样式*/
  .upload-box {
    padding: 0 15px;
    height: 96px;
    margin: 10px 0;
  }

  .photos-box {
    width: 100%;
  }

  .photos-box .color-box {
    display: block;
    position: relative;
    width: 77px;
    height: 77px;
    margin-right: 15px;
    margin-bottom: 15px;
    border-radius: 5px;
    overflow: hidden;
  }

  .photos-box .color-show {
    display: inline-block;
    flex-wrap: wrap;
    padding: 0 0;
  }

  .photos-box .color-box img {
    width: 100%;
    height: 100%;
  }

  .photos-box .color-box a {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
  }

  .photos-box .color-box:hover a {
    display: block;
  }

  .photos-box .color-box .glyphicon {
    width: 100%;
    height: 100%;
    color: #aeaeae;
    display: block;
    text-align: center;
    line-height: 77px;
    background: rgba(0, 0, 0, .4);
    border-radius: 5px;
  }

  .photos-box .color-box a.add-photos {
    display: block;
    box-sizing: border-box;
    border: 1px dashed #D8DCE5;
    border-radius: 5px;
  }

  .photos-box .color-box a.add-photos:hover {
    border: 1px dashed #409EFF;
  }
</style>
